package cn.wolfcode.ssm.service.impl;

import cn.wolfcode.ssm.domain.Employee;
import cn.wolfcode.ssm.domain.Notice;
import cn.wolfcode.ssm.mapper.NoticeMapper;
import cn.wolfcode.ssm.qo.QueryObject;
import cn.wolfcode.ssm.service.INoticeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;
    @Override
    public void delete(Long id) {
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Notice notice) {
        Employee employee = (Employee)SecurityUtils.getSubject().getPrincipal();
        notice.setIssuer(employee);
        notice.setPubdate(new Date());
        noticeMapper.insert(notice);
    }

    @Override
    public Notice getOne(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> getAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }


    @Override
    public PageInfo<Notice> selctForPageResult(QueryObject qo) {
        //使用分页插件,传入当前页,每页显示数量
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        Employee employee =(Employee) SecurityUtils.getSubject().getPrincipal();
        //通过当前用户id查询出它看过的所有通告
        List<Long> noticeIds=noticeMapper.getNotice(employee.getId());
        //通过分页查询出的结果集
        List<Notice> notices = noticeMapper.selectForResult(qo);
        //将结果集中的通告与当前用户的所有通告进行比对,如果id相同,将通告状态设置为true
        for(Notice n:notices){
            for (Long noticeId : noticeIds) {
                Notice one = noticeMapper.selectByPrimaryKey(noticeId);
                if(n.getId()==one.getId()){
                    n.setStatus(true);
                }
            }
        }
        return new PageInfo(notices);
    }

    @Override
    public void insertRelation(Long noticeId, Long employeeId) {
        noticeMapper.insertRelation(noticeId,employeeId);
    }


    @Override
    public void deleteRelation(Long id) {
        noticeMapper.deleteRelation(id);
    }

    @Override
    public  List<Long>  getNotice(Long id) {
        return noticeMapper.getNotice(id);
    }
}
